<template>
  <div class="trash-bin-container">
    <el-card class="trash-bin-header">
      <div class="trash-header-content">
        <div class="trash-title">
          <el-icon><delete /></el-icon>
          <h2>{{ t('trash.title') }}</h2>
        </div>
        
        <div class="trash-actions">
          <el-tooltip :content="t('trash.emptyTrashTooltip')">
            <el-button 
              type="danger" 
              :disabled="!hasTrashCards" 
              @click="confirmEmptyTrash"
              :title="t('trash.emptyTrash')"
            >
              {{ t('trash.emptyTrash') }}
            </el-button>
          </el-tooltip>
        </div>
      </div>
      <el-alert v-if="!hasTrashCards" :title="t('trash.emptyAlert')" type="info" show-icon />
      <el-alert v-if="hasTrashCards" :title="t('trash.explanation')" type="warning" show-icon />
    </el-card>

    <div class="trash-bin-content">
      <!-- 加载指示器 -->
      <div v-if="loading" class="loading-container">
        <el-icon class="loading-icon">
          <component :is="Loading" />
        </el-icon>
        <span>{{ t('common.loading') }}</span>
      </div>

      <!-- 卡片列表 -->
      <el-table
        v-else
        ref="multipleTable"
        :data="cards"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :empty-text="t('trash.noCards')"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" :index="indexMethod" width="60" :label="t('common.index')" />
        
        <el-table-column prop="title" :label="t('common.title')" show-overflow-tooltip>
          <template #default="scope">
            <span class="card-title-text">{{ scope.row.title || t('common.untitled') }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="tags" :label="t('common.tags')" width="240" show-overflow-tooltip>
          <template #default="scope">
            <div class="tag-container">
              <template v-if="scope.row.tags && scope.row.tags.length">
                <el-tag 
                  v-for="tag in scope.row.tags.slice(0, 3)" 
                  :key="tag"
                  size="small"
                  class="card-tag"
                >
                  {{ tag }}
                </el-tag>
                <span v-if="scope.row.tags.length > 3" class="more-tags">+{{ scope.row.tags.length - 3 }}</span>
              </template>
              <span v-else>{{ t('common.noTags') }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column :label="t('trash.trashedDate')" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.trashedAt) }}
          </template>
        </el-table-column>
        
        <el-table-column :label="t('common.operations')" width="240" fixed="right">
          <template #default="scope">
            <div class="operations-container">
              <el-tooltip :content="t('trash.restoreTooltip')">
                <el-button 
                  type="success" 
                  size="small" 
                  plain
                  @click.stop="restoreCard(scope.row)"
                >
                  {{ t('trash.restore') }}
                </el-button>
              </el-tooltip>
              
              <el-tooltip :content="t('trash.deleteTooltip')">
                <el-button 
                  type="danger" 
                  size="small"
                  @click.stop="confirmPermanentDelete(scope.row)"
                >
                  {{ t('trash.delete') }}
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作按钮 -->
      <div v-if="cards.length > 0" class="batch-actions">
        <el-button
          type="primary"
          :disabled="multipleSelection.length === 0"
          @click="batchRestore"
        >
          {{ t('trash.batchRestore', { count: multipleSelection.length }) }}
        </el-button>
        
        <el-button
          type="danger"
          :disabled="multipleSelection.length === 0"
          @click="batchDelete"
        >
          {{ t('trash.batchDelete', { count: multipleSelection.length }) }}
        </el-button>
      </div>
      
      <!-- 分页器 -->
      <div class="pagination-container" v-if="totalCards > 0">
        <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCards"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Loading } from '@element-plus/icons-vue';
import { useI18n } from 'vue-i18n';
import type { CardItem } from '../types/cardData';
import { formatDateTimeSync as formatDateUtil } from '../utils/dateFormatter';

const { t } = useI18n();

// 状态
const loading = ref(true);
const cards = ref<CardItem[]>([]);
const currentPage = ref(1);
const pageSize = ref(20);
const totalCards = ref(0);
const multipleSelection = ref<CardItem[]>([]);
const multipleTable = ref<any>(null);

// 计算属性
const hasTrashCards = computed(() => totalCards.value > 0);

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '';
  return formatDateUtil(dateString);
};

// 加载垃圾站中的卡片
const loadTrashCards = async () => {
  loading.value = true;
  try {
    const result = await window.electronAPI.getTrashCards(currentPage.value, pageSize.value);
    cards.value = result.cards || [];
    totalCards.value = result.total || 0;
  } catch (error) {
    console.error('Failed to load trash cards:', error);
    ElMessage.error(t('trash.loadFailed'));
  } finally {
    loading.value = false;
  }
};

// 恢复卡片
const restoreCard = async (card: CardItem) => {
  try {
    const success = await window.electronAPI.restoreCardFromTrash(card.id);
    if (success) {
      ElMessage.success(t('trash.restoreSuccess'));
      await loadTrashCards();
    } else {
      ElMessage.error(t('trash.restoreFailed'));
    }
  } catch (error) {
    console.error('Failed to restore card:', error);
    ElMessage.error(t('trash.restoreFailed'));
  }
};

// 确认永久删除
const confirmPermanentDelete = (card: CardItem) => {
  ElMessageBox.confirm(
    t('trash.deleteConfirm'),
    t('common.confirm'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    try {
      const success = await window.electronAPI.permanentlyDeleteCard(card.id);
      if (success) {
        ElMessage.success(t('trash.deleteSuccess'));
        await loadTrashCards();
      } else {
        ElMessage.error(t('trash.deleteFailed'));
      }
    } catch (error) {
      console.error('Failed to permanently delete card:', error);
      ElMessage.error(t('trash.deleteFailed'));
    }
  }).catch(() => {
    // User cancelled, do nothing
  });
};

// 确认清空垃圾站
const confirmEmptyTrash = () => {
  ElMessageBox.confirm(
    t('trash.emptyTrashConfirm'),
    t('common.confirm'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    try {
      const success = await window.electronAPI.emptyTrash();
      if (success) {
        ElMessage.success(t('trash.emptyTrashSuccess'));
        await loadTrashCards();
      } else {
        ElMessage.error(t('trash.emptyTrashFailed'));
      }
    } catch (error) {
      console.error('Failed to empty trash:', error);
      ElMessage.error(t('trash.emptyTrashFailed'));
    }
  }).catch(() => {
    // User cancelled, do nothing
  });
};

// 处理表格选择变化
const handleSelectionChange = (selection: CardItem[]) => {
  multipleSelection.value = selection;
};

// 计算行号
const indexMethod = (index: number) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};

// 批量恢复
const batchRestore = async () => {
  if (multipleSelection.value.length === 0) return;
  
  ElMessageBox.confirm(
    t('trash.batchRestoreConfirm', { count: multipleSelection.value.length }),
    t('common.confirm'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    loading.value = true;
    let successCount = 0;
    
    try {
      for (const card of multipleSelection.value) {
        const success = await window.electronAPI.restoreCardFromTrash(card.id);
        if (success) {
          successCount++;
        }
      }
      
      if (successCount > 0) {
        ElMessage.success(t('trash.batchRestoreSuccess', { count: successCount }));
        // 重新加载数据
        await loadTrashCards();
        // 清除选择
        if (multipleTable.value) {
          multipleTable.value.clearSelection();
        }
      } else {
        ElMessage.error(t('trash.batchRestoreFailed'));
      }
    } catch (error) {
      console.error('Failed to batch restore cards:', error);
      ElMessage.error(t('trash.batchRestoreFailed'));
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // User cancelled, do nothing
  });
};

// 批量删除
const batchDelete = async () => {
  if (multipleSelection.value.length === 0) return;
  
  ElMessageBox.confirm(
    t('trash.batchDeleteConfirm', { count: multipleSelection.value.length }),
    t('common.confirm'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    loading.value = true;
    let successCount = 0;
    
    try {
      for (const card of multipleSelection.value) {
        const success = await window.electronAPI.permanentlyDeleteCard(card.id);
        if (success) {
          successCount++;
        }
      }
      
      if (successCount > 0) {
        ElMessage.success(t('trash.batchDeleteSuccess', { count: successCount }));
        // 重新加载数据
        await loadTrashCards();
        // 清除选择
        if (multipleTable.value) {
          multipleTable.value.clearSelection();
        }
      } else {
        ElMessage.error(t('trash.batchDeleteFailed'));
      }
    } catch (error) {
      console.error('Failed to batch delete cards:', error);
      ElMessage.error(t('trash.batchDeleteFailed'));
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // User cancelled, do nothing
  });
};

// 处理分页变化
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  loadTrashCards();
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  loadTrashCards();
};

// 生命周期钩子
onMounted(() => {
  loadTrashCards();
});
</script>

<style scoped>
.trash-bin-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.trash-bin-header {
  margin-bottom: 20px;
}

.trash-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.trash-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.trash-title h2 {
  margin: 0;
}

.trash-bin-content {
  flex: 1;
  overflow: auto;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.loading-icon {
  font-size: 24px;
  margin-bottom: 10px;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.card-title-text {
  font-weight: 500;
}

.tag-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 5px;
}

.card-tag {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.more-tags {
  color: #909399;
  font-size: 12px;
}

.operations-container {
  display: flex;
  gap: 8px;
}

.batch-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>